package com.hh.fudan.project_management;

import java.io.IOException;
import java.net.URL;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.test.NotificationSpider;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;

import com.hh.fudan.project_management.adapters.SearchAdapter;
import com.hh.fudan.project_management.basic.Global;
import com.hh.fudan.project_management.basic.TextUtil;
import com.hh.fudan.project_management.bean.ListItemResult;

public class NotificationViewActivity extends Activity {
	Toast toast;
	private ListView lv;
	private List<ListItemResult> searchResultList = new ArrayList<ListItemResult>();
	private List<String> images = new ArrayList<String>();
	private SharedPreferences prefs;
	private int curPage = 0;
	private int lastVisibleItem = 0;
	private TextView viewMore;
	private SearchAdapter searchAdapter;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.notification_layout);
		viewMore = (TextView) findViewById(R.id.view_more2);
		viewMore.setVisibility(View.GONE);
		viewMore.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (!viewMore.getText().equals("更多"))
					return;
				new LoadingMoreItems().execute();
			}
		});
	}

	@Override
	public void onResume() {
		super.onResume();

		try {
			URL url = generateURL();
			parseResult(url);
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		if (searchResultList.size() != 0) {
			loadImages();
			showResults();
		}
		if (NotificationSpider.enterFromNotif) {
			NotificationSpider.enterFromNotif = false;
			NotificationSpider.setLastTime(new Date());
		}
	}

	/*
	 * generate request url
	 */
	public URL generateURL() throws JDOMException, IOException {

		Calendar calendar = Calendar.getInstance();
		if (NotificationSpider.lastTime == null)
			NotificationSpider.lastTime = calendar.getTime();
		
		String paras = "";
		int page = ++curPage;
		int pageSize = Global.PAGINATION;
		paras += "?page=" + page + "&pageSize=" + pageSize + "&";
		prefs = getSharedPreferences("usersettings", 0);
		String cityName = URLEncoder.encode(prefs.getString("cityName", ""),
				"UTF-8");
		String title = TextUtil.splitMultiKeywords(prefs.getString("title", "")
				.replaceAll(",", " "));
		String price = prefs.getString("price", "");
		String discountPercent = prefs.getString("discountPercent", "");
		String members = prefs.getString("members", "0");

		System.out.println("price:" + price);
		paras += "createTime=" + NotificationSpider.lastTime.getTime()
				+ "&discountPercent=" + discountPercent + "&cityName="
				+ cityName + "&title=" + title + "&price=" + price
				+ "&members=" + members;
		System.out.println(paras);
		URL url = new URL(Global.SERVER_URL_BASE + paras);

		return url;
	}

	/*
	 * parse XML
	 */
	public void parseResult(URL url) throws JDOMException, IOException {
		searchResultList.clear();
		SAXBuilder builder = new SAXBuilder(false);
		Document doc = builder.build(url);

		Element root = doc.getRootElement();
		List<Element> list = root.getChildren();
		int size = list.size();

		for (int i = 0; i < size; i++) {
			Element item = list.get(i);
			String title = item.getChildText("title");
			if (title.length() > 40) {
				title = title.substring(0, 40) + "...";
			}
			String price = item.getChildText("price");
			String dealValue = item.getChildText("dealValue");

			searchResultList.add(new ListItemResult(item.getChildText("oid"),
					item.getChildText("lImageUrl"), title, price.substring(0,
							price.indexOf(".")), dealValue.substring(0,
							dealValue.indexOf(".")), item
							.getChildText("discountPercent")));
		}

		double prefLatitude = (double) prefs.getFloat("latitude", 0);
		double prefLongitude = (double) prefs.getFloat("longitude", 0);
		Location prefLocation = new Location("prefl");
		prefLocation.setLatitude(prefLatitude);
		prefLocation.setLongitude(prefLongitude);

		int prefDistance = prefs.getInt("distance", 0);

		for (int i = 0; i < list.size(); i++) {
			Element shopsNode = list.get(i).getChild("shops");
			List<Element> shops = shopsNode.getChildren();
			boolean flag = false;
			for (int j = 0; j < shops.size(); j++) {
				Element shopNode = shops.get(j);
				double latitude = Double.parseDouble(shopNode
						.getChildText("longtitude"));
				double longitude = Double.parseDouble(shopNode
						.getChildText("latitude"));

				if ((latitude > 0) && (longitude > 0)) {
					Location location = new Location("l1");
					location.setLatitude(latitude);
					location.setLongitude(longitude);

					System.out.println("current:" + prefLatitude + ","
							+ prefLongitude + ";shop:" + latitude + ","
							+ longitude);
					double distance = location.distanceTo(prefLocation);
					DecimalFormat formatter = new DecimalFormat("#.000");
					System.out.println("distance to the shop:"
							+ formatter.format(distance));

					if (distance < prefDistance)
						flag = true;
				}

			}
			if (flag)
				searchResultList.get(i).setNearBy(true);
		}

	}

	/*
	 * show in the list view
	 */
	public void showResults() {

		lv = (ListView) findViewById(R.id.notification_list_view);

		List<HashMap<String, Object>> mlist = new ArrayList<HashMap<String, Object>>();
		int size = searchResultList.size();
		for (int i = 0; i < size; i++) {
			ListItemResult result = searchResultList.get(i);
			HashMap<String, Object> mMap = new HashMap<String, Object>();
			// mMap.put("image", imageList.get(i));
			mMap.put("image", images.get(i));
			mMap.put("title", result.getTitle());
			mMap.put("price", result.getPrice());
			mMap.put("dealValue", result.getDealValue());
			mMap.put("oid", result.getOid());
			mMap.put("nearby", result.isNearBy());
			mlist.add(mMap);
		}

		searchAdapter = new SearchAdapter(this, mlist, R.layout.list_item,
				new String[] { "image", "title", "price", "dealValue", "oid",
						"nearby" }, new int[] { R.id.image_deal,
						R.id.deal_title, R.id.deal_price, R.id.deal_dealValue,
						R.id.deal_oid, R.id.image_nearby });

		lv.setAdapter(searchAdapter);
		lv.setTextFilterEnabled(true);
		lv.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				lastVisibleItem = firstVisibleItem + visibleItemCount;
				if (lastVisibleItem > 0 && lastVisibleItem == totalItemCount) {
					viewMore.setVisibility(View.VISIBLE);
				} else
					viewMore.setVisibility(View.GONE);
				Log.i("last visible item count", lastVisibleItem + "");
			}

			@Override
			public void onScrollStateChanged(AbsListView view, int state) {

			}
		});
		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> av, View v, int pos, long id) {
				String oid = ((TextView) findViewById(R.id.deal_oid)).getText()
						.toString();
				Intent viewDetail = new Intent(NotificationViewActivity.this,
						DetailActivity.class);
				viewDetail.putExtra("oid", oid);
				startActivity(viewDetail);
			}
		});
	}

	/*
	 * load images
	 */
	private void loadImages() {
		images.clear();
		int size = searchResultList.size();
		for (int i = 0; i < size; i++) {
			ListItemResult result = searchResultList.get(i);
			String imageUrl = result.getUrl();
			images.add(imageUrl);
		}

	}

	private void showMoreResults() {
		List<HashMap<String, Object>> mlist = new ArrayList<HashMap<String, Object>>();

		int size = searchResultList.size();
		if (size == 0)
			return;
		for (int i = 0; i < size; i++) {
			ListItemResult result = searchResultList.get(i);
			HashMap<String, Object> mMap = new HashMap<String, Object>();
			Log.i("null", "imageList ");
			mMap.put("image", images.get(i));
			// mMap.put("image", R.drawable.icon);
			mMap.put("title", result.getTitle());
			mMap.put("price", result.getPrice());
			mMap.put("dealValue", result.getDealValue());
			mMap.put("oid", result.getOid());
			mlist.add(mMap);
		}
		searchAdapter.appendData(mlist);
		searchAdapter.notifyDataSetChanged();
	}

	private class LoadingMoreItems extends AsyncTask<String, Void, Void> {
		private boolean moreItems = false;

		@Override
		protected void onPreExecute() {
			viewMore.setText("加载中...");
			viewMore.setVisibility(View.VISIBLE);
		}

		@Override
		protected Void doInBackground(String... arg0) {
			try {

				URL url = generateURL();
				parseResult(url);
			} catch (JDOMException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

			if (searchResultList.size() != 0) {
				if (searchResultList.size() % Global.PAGINATION == 0) {
					moreItems = true;
				}
				loadImages();

			} else
				moreItems = false;

			return null;
		}

		@Override
		protected void onPostExecute(Void unused) {
			if (moreItems) {
				viewMore.setText("更多");
			} else {
				viewMore.setText("没有更多了");
			}
			showMoreResults();
		}
	}

}
